package com.ai.platform.rpc.service.impl;

import com.ai.platform.model.dto.Input;
import com.ai.platform.model.dto.Output;
import com.ai.platform.core.constant.IConstants;
import com.ai.platform.core.exception.BusinessException;
import com.ai.platform.core.rpc.ApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import java.lang.reflect.Method;

/**
 * Created by yeyingsheng on 2018/4/23.
 * 统一接口实现
 */
public class ApiServiceImpl implements ApiService,BeanFactoryAware {

    private static final Logger logger = LoggerFactory.getLogger(ApiServiceImpl.class);

    private BeanFactory beanFactory;

    @Override
    public Output execute(Input input) {
        long startTime=System.currentTimeMillis();
        Output output=new Output();
        try {
            if(null==input || null==input.getServiceName() || null==input.getMethod()){
                throw new BusinessException("调用服务缺少参数");
            }
            output.setCode(IConstants.SUCCESS);
            Object object=beanFactory.getBean(input.getServiceName());

            Method method=object.getClass().getMethod(input.getMethod(),Input.class,Output.class);
            method.invoke(object,input,output);
        } catch (Exception e) {
            if(e instanceof BusinessException){
                BusinessException businessException= (BusinessException) e;
                output.setCode(businessException.getCode());
                output.setMsg(businessException.getMsg());
            }else{
                output.setCode(IConstants.UNKNOWN_ERROR);
                output.setMsg(e.getMessage());
            }
            e.printStackTrace();
        }
        long endTime=System.currentTimeMillis();
        long cost=endTime-startTime;
        output.setStartTime(startTime);
        output.setEndTime(endTime);
        output.setCost(cost);
        logger.info("调用后台服务完成！service=" + input.getServiceName() + "，method=" + input.getMethod() + "，cost=" + cost + "ms");
        return output;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory=beanFactory;
    }
}